<template>
  <a-modal
    v-model="visible"
    title="节点心跳"
    @cancel="close"
    width="70%"
  >
    <div id="heartDiv" style="height: 300px;width: 100%">
    </div>
  </a-modal>
</template>
<script>
import * as echarts from 'echarts/core';
import moment from 'moment'
import {getHeartsSchedule, getLastDayHearts} from '@/api/rootheartBeat'


import {GridComponent, TitleComponent, TooltipComponent} from 'echarts/components';
import {LineChart} from 'echarts/charts';
import {CanvasRenderer} from 'echarts/renderers';

echarts.use(
  [TitleComponent, TooltipComponent, GridComponent, LineChart, CanvasRenderer]
);


export default {
  data: function () {
    return {
      labelCol: {span: 4},
      wrapperCol: {span: 14},
      other: '',
      visible: false,
      heartData: [],
      nodeId: null,
      lastDate: null,
      scheduleId: null,
      option: {
        title: {
          text: '心跳图'
        },
        tooltip: {

          trigger: 'axis', //触发类型；轴触发，axis则鼠标hover到一条柱状图显示全部数据，item则鼠标hover到折线点显示相应数据，
          confine: false,
          formatter: function (params) {
            console.log(params)
            params = params[0];
            var date = new Date(params.name);
            return moment(date).format("YYYY-MM-DD HH:mm:ss") + ' : ' + (params.value[1] == 1 ? '在线' : '离线');
          },
          axisPointer: {
            animation: false
          }
        },
        grid: {
          left: 30,
          right: 20,
          bottom: 30
        },
        xAxis: {
          type: 'time',
          splitLine: {
            show: false
          },
          nameTextStyle: {
            color: "rgba(132, 42, 42, 1)"
          }

        },
        yAxis: {
          type: 'value',
          boundaryGap: false,
          splitLine: {
            show: false
          },
          show: true,
          axisLabel: {
            formatter(value) {
              let text = ''
              if (value === 0) {
                text = '离线'
              } else if (value === 1) {
                text = '在线'
              }
              return text
            }
          }
        },
        series: [{
          name: '模拟数据',
          type: 'line',
          showSymbol: false,
          hoverAnimation: false,
          data: []
        }]
      }

    }
  },
  mounted() {

  },
  methods: {
    async initData(node) {
      this.visible = true
      this.nodeId = node.id;
      await this.getDayHearts(this.nodeId);

      this.$nextTick(() => {
        var chartDom = document.getElementById('heartDiv');
        var myChart = echarts.init(chartDom);
        this.option.series[0].data = this.heartData
        myChart.setOption(this.option);

        let _this = this;
        this.scheduleId = setInterval(function () {
          _this.getHeartsSchedule(myChart);
        }, 30 * 1000);
      });
    },
    async getDayHearts() {
      await getLastDayHearts(this.nodeId).then((res) => {
        if (res.code === '0') {
          res.data.forEach(item => {
            this.heartData.push({
              name: new Date(item.insertdate).toString(),
              value: [
                new Date(item.insertdate),
                item.status,
              ]
            })
          })
          this.lastDate = res.data[res.data.length - 1] ? res.data[res.data.length - 1].insertdate : new Date()
        }
      })
    },
    getHeartsSchedule(myChart) {
      getHeartsSchedule(this.nodeId, new Date(this.lastDate).toString()).then((res) => {
        if (res.code === '0') {

          if (this.heartData.length > 3000) {
            res.data.forEach(item => {
              this.heartData.shift();
            })
          }

          res.data.forEach(item => {
            this.heartData.push({
              name: new Date(item.insertdate).toString(),
              value: [
                new Date(item.insertdate),
                item.status,
              ]
            })
          })

          console.log(this.heartData.length)
          myChart.setOption({
            series: [{
              data: this.heartData
            }]
          });
        }
      })
    },
    randomData() {
      now = moment(now).add('seconds', 10).toDate()
      value = Math.floor(Math.random() * (50 - 1 + 1) + 1)
      return {
        name: now.toString(),
        value: [
          now,
          value
        ]
      };
    },
    close() {
      clearInterval(this.scheduleId)
      this.heartData = []
      this.visible = false
    }
  }
}
</script>
